#include "KPHelper.h"

#include <unistd.h>

#include <sys/socket.h>

pthread_mutex_t KPHelper::m_sMutexes[MAX_MUTEXES];

void KPHelper::sendGLObjectToClient(int client, KPGLObject& obj)
{
	KPMessage* msg = obj.toMessage();
	sendMessageToClient(client, *msg);
	SAFE_DEL(msg);
}

void KPHelper::sendMessageToClient(int client, KPMessage& msg)
{
	int tmp = (int)msg.m_type;
	send(client, &tmp, 4, 0);
	send(client, &msg.m_length, 4, 0);
	if (msg.m_length > 0 && msg.m_pData)
	{
		send(client, msg.m_pData, msg.m_length, 0);
	}
}

void KPHelper::sendFinishCaptureMessageToClient(int client)
{
	KPMessage msg;
	msg.m_type = KMT_FINISH_CAPTURE;
	sendMessageToClient(client, msg);
}

void KPHelper::sendSuccessMessageToClient(int client)
{
	KPMessage msg;
	msg.m_type = KMT_SUCCESS;
	sendMessageToClient(client, msg);
}

void KPHelper::sendFailedMessageToClient(int client)
{
	KPMessage msg;
	msg.m_type = KMT_FAILED;
	sendMessageToClient(client, msg);
}

void KPHelper::closeSocket(int sockId)
{
	close(sockId);
}

void KPHelper::initMutexes()
{
	for (int i = 0; i < MAX_MUTEXES; i++)
	{
		pthread_mutex_init(&m_sMutexes[i], NULL);
	}
}

void KPHelper::destroyMutexes()
{
	for (int i = 0; i < MAX_MUTEXES; i++)
	{
		pthread_mutex_destroy(&m_sMutexes[i]);
	}
}

void KPHelper::LockMutex0()
{
	pthread_mutex_lock(&m_sMutexes[0]);
}

void KPHelper::UnlockMutex0()
{
	pthread_mutex_unlock(&m_sMutexes[0]);
}
